//
//  GoodsCategoryView.m
//  phmall
//
//  Created by admin on 2017/10/21.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "GoodsCategoryView.h"
#import "GoodsListCell.h"
#import "CategoryModel.h"
#import "GoodsModel.h"
#import "ShopInfoModel.h"
#import "PersonalCenterVC.h"
#import "LevelImageView.h"
//#import "SearchViewController.h"
#import "CommodityDetailsVC.h"
@interface GoodsCategoryView ()<UICollectionViewDelegate,UICollectionViewDataSource,SDCycleScrollViewDelegate,UITabBarControllerDelegate,GoodsListCellDelegate,DZNEmptyDataSetDelegate,DZNEmptyDataSetSource>
//轮播图
@property(nonatomic,strong)SDCycleScrollView *scrollView;

@property(nonatomic,strong)UICollectionView *collectionView;
//分类名数组
@property(nonatomic,strong)NSMutableArray *categoryArry;
//商品名数组
@property(nonatomic,strong)NSMutableArray *goodsArry;
//轮播图数组
@property(nonatomic,strong)NSMutableArray *cycleArry;
//商店信息
@property(nonatomic,strong)ShopInfoModel *shopInfo;

/* 滚回顶部按钮 */
@property(nonatomic,strong)UIButton *backTopButton;
@end



@implementation GoodsCategoryView

-(void)moreAction:(UICollectionViewCell *)cell{
    for (int i=0; i<self.goodsArry.count; i++) {
        NSMutableArray *goodsArr=self.goodsArry[i];
        for (int j=0; j<goodsArr.count; j++) {
            NSIndexPath *index1 =  [NSIndexPath indexPathForItem:j inSection:i];
            GoodsListCell *goodsCell=(GoodsListCell *)[self.collectionView cellForItemAtIndexPath:index1];
            if (cell!=goodsCell) {
                [goodsCell moreViewTapAction];
            }
            
        }
    }
}
-(instancetype)init{
    if ([super init]) {
        self.emptyType=EmptyDataSetNone;
        //绘制界面
        [self addSubview:self.collectionView];
        [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self);
            make.left.equalTo(self);
            make.right.equalTo(self);
            make.bottom.equalTo(self).with.offset(0).priorityHigh();
        }];
    }
    return self;
}

#pragma mark - 数据转model并缓存
- (void)analysisDataWithCategoryArray:(NSMutableArray *)array{
    self.emptyType=EmptyDataSetNoData;
    for (NSDictionary *dict in array)
    {
        CategoryModel *model = [CategoryModel yy_modelWithDictionary:dict];
        [self.categoryArry addObject:model];
    }
    [self.collectionView reloadData];
}
#pragma mark - 数据转model并缓存
- (void)analysisDataWithCycleDictionary:(NSDictionary*)dictionary{
    self.shopInfo = [ShopInfoModel yy_modelWithDictionary:dictionary];
    [self.collectionView reloadData];
}

#pragma mark - 轮播图片点击
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    NSLog(@"---点击了第%ld张图片", (long)index);
}
#pragma mark collectionView代理方法
//返回section个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.categoryArry.count;
}

//每个section的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    CategoryModel *model =self.categoryArry[section];
    return model.goods_list.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId=@"cellId";
    GoodsListCell *cell = (GoodsListCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
    CategoryModel *model =self.categoryArry[indexPath.section];
    cell.model=model.goods_list[indexPath.row];
    cell.delegate=self;
    ViewBorderRadius(cell, 10, 0, [UIColor clearColor]);
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    //    return CGSizeMake(SCREEN_WIDTH, _header.height);
    if (section == 0) {
        return CGSizeMake(SCREEN_WIDTH, 384);
    }else{
        return CGSizeMake(SCREEN_WIDTH, 54);
    }
    
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    return CGSizeMake(SCREEN_WIDTH, 35);
}
//设置每个item的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (iPhone5SE) {
        return CGSizeMake(SCREEN_WIDTH/2-15, 230);
    }else  if (iPhone6_6s) {
        return CGSizeMake(SCREEN_WIDTH/2-15, 252);
    }else  if (iPhone6Plus_6sPlus) {
        return CGSizeMake(SCREEN_WIDTH/2-15, 272);
    }else{
        return CGSizeMake(SCREEN_WIDTH/2-15, 252);
    }
}
//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

//设置每个item垂直间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

//通过设置SupplementaryViewOfKind 来设置头部或者底部的view，其中 ReuseIdentifier 的值必须和 注册是填写的一致，本例都为 “reusableView”
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    // 1.定义重用标识
    static NSString *headerID;
    //    UICollectionReusableView *reusableView = nil;
    if (indexPath.section == 0) {
        headerID = @"headerSelectType";
    } else {
        headerID = @"headerDisplay";
    }
//    CategoryModel *model=self.categoryArry[indexPath.section];
    
    static NSString *footerID = @"FooterSelectType";
    UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerID forIndexPath:indexPath];
    
    UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerID forIndexPath:indexPath];
    CategoryModel *model=self.categoryArry[indexPath.section];
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        headerView.backgroundColor=[UIColor groupTableViewBackgroundColor];
        for (UIView *view in headerView.subviews) {
            [view removeFromSuperview];
        }
        if (indexPath.section == 0) {
            
            //轮播图
            _scrollView = [[SDCycleScrollView alloc] init];
            _scrollView.autoScrollTimeInterval=5;
            _scrollView.bannerImageViewContentMode=UIViewContentModeScaleAspectFill;
            _scrollView.placeholderImage=[UIImage imageNamed:@"图片空白页"];
            _scrollView.pageControlStyle=SDCycleScrollViewPageContolStyleAnimated;
            _scrollView.pageControlDotSize=CGSizeMake(7, 7);
            [headerView addSubview:_scrollView];
            _scrollView.delegate=self;
            [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(headerView);
                make.left.equalTo(headerView);
                make.right.equalTo(headerView);
                make.height.mas_equalTo(200);
            }];
            _scrollView.bannerImageViewContentMode=UIViewContentModeScaleAspectFill;
            //轮播图数据
            NSMutableArray *cycle=[[NSMutableArray alloc] init];
            for (cycleModel *cModel in self.shopInfo.cycle) {
                [cycle addObject:[NSString stringWithFormat:@"%@union/%@",IMGURL,cModel.img]];
            }
            _scrollView.imageURLStringsGroup=cycle;
            
            //商店背景
            UIView *store=[[UIView alloc] init];
            store.backgroundColor=[UIColor whiteColor];
            [headerView addSubview:store];
            [store mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(_scrollView.mas_bottom).with.offset(10);
                make.left.equalTo(self);
                make.right.equalTo(self);
                make.height.mas_equalTo(120);
            }];
            
            //关注按钮
            UIButton *enshrine=[UIButton buttonWithType:UIButtonTypeCustom];
            [enshrine setImage:[UIImage imageNamed:@"关注未点亮"] forState:UIControlStateNormal];
            [enshrine setImage:[UIImage imageNamed:@"关注点亮"] forState:UIControlStateSelected];
            [headerView addSubview:enshrine];
            [enshrine mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(store).with.offset(10);
                make.right.equalTo(store).with.offset(-10);
                make.width.height.mas_offset(20);
            }];
            //商店Logo
            UIImageView *storeImg=[[UIImageView alloc] init];
            [storeImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@union/%@",IMGURL,self.shopInfo.up_logo]]];
            [headerView addSubview:storeImg];
            [storeImg mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(store).with.offset(10);
                make.left.equalTo(store).with.offset(10);
                make.width.mas_equalTo(70);
                make.height.mas_equalTo(70);
            }];
            
            LevelImageView *level=[[LevelImageView alloc]init];
            level.score=[self.shopInfo.shop_level intValue];
            NSLog(@"%d",[self.shopInfo.shop_level intValue]);
            [headerView addSubview:level];
            [level mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(storeImg);
                make.left.equalTo(storeImg.mas_right).with.offset(10);
                make.right.equalTo(headerView).offset(-10);
                make.height.offset(20);
            }];
            
            //商店名称
            UILabel *storeName=[[UILabel alloc] init];
            storeName.text=self.shopInfo.shop_name;
            [headerView addSubview:storeName];
            storeName.font=[UIFont systemFontOfSize:16];
            storeName.textColor=[UIColor colorWithHexString:@"#121212"];
            [storeName mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(level.mas_top).with.offset(-7);
                make.left.equalTo(level);
            }];
            //商店联系方式
            UILabel *phone=[[UILabel alloc]init];
            phone.text=[NSString stringWithFormat:@"%@:%@",Localized(@"联系方式"),self.shopInfo.tel];
            phone.textColor=[UIColor colorWithHexString:@"#808080"];
            phone.font=[UIFont systemFontOfSize:13];
            [headerView addSubview:phone];
            [phone mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(level.mas_bottom).with.offset(7);
                make.left.equalTo(level);
            }];
            //分割线
            UIView *line=[[UIView alloc] init];
            line.backgroundColor=[UIColor colorWithHexString:@"#efeff4"];
            [headerView addSubview:line];
            [line mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(storeImg.mas_bottom).with.offset(10);
                make.left.equalTo(store).with.offset(10);
                make.right.equalTo(store).with.offset(-10);
                make.height.mas_offset(1);
            }];
            //信用保障
            UIImageView *ensureImg=[[UIImageView alloc] init];
            [headerView addSubview:ensureImg];
            ensureImg.image=[UIImage imageNamed:@"保障"];
            [ensureImg mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(storeImg);
                make.top.equalTo(line).with.offset(8);
                make.width.mas_offset(14);
                make.height.mas_offset(14);
            }];
            UILabel *ensure=[[UILabel alloc] init];
            [headerView addSubview:ensure];
            ensure.text=Localized(@"菲信担保");
            ensure.font=[UIFont systemFontOfSize:11];
            [ensure mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(ensureImg.mas_right).with.offset(11);
                make.centerY.equalTo(ensureImg);
            }];
            //分类
            UIView *category=[[UIView alloc] init];
            [headerView addSubview:category];
            category.backgroundColor=[UIColor whiteColor];
            [category mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(store.mas_bottom).with.offset(10);
                make.left.right.equalTo(headerView);
                make.height.mas_offset(44);
            }];
            //装饰线
            UIImageView *img=[[UIImageView alloc] init];
            [headerView addSubview:img];
            img.backgroundColor=[UIColor orangeColor];
            [img mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(category).with.offset(7);
                make.bottom.equalTo(category).with.offset(-7);
                make.left.equalTo(category).with.offset(10);
                make.width.mas_offset(5);
            }];
            //分类名称
            UILabel *categoryName=[[UILabel alloc] init];
            categoryName.text=model.category_name;
            categoryName.font=[UIFont systemFontOfSize:17];
            categoryName.textColor=[UIColor colorWithHexString:@"#121212"];
            [headerView addSubview:categoryName];
            [categoryName mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(img).with.offset(10);
                make.centerY.equalTo(img);
            }];
        }else{
            //分类
            UIView *category=[[UIView alloc] init];
            [headerView addSubview:category];
            category.backgroundColor=[UIColor whiteColor];
            [category mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(headerView).with.offset(10);
                make.left.right.equalTo(headerView);
                make.height.mas_offset(44);
            }];
            //装饰线
            UIImageView *img=[[UIImageView alloc] init];
            [headerView addSubview:img];
            img.backgroundColor=[UIColor orangeColor];
            [img mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(category).with.offset(7);
                make.bottom.equalTo(category).with.offset(-7);
                make.left.equalTo(category).with.offset(10);
                make.width.mas_offset(5);
            }];
            //分类名称
            UILabel *categoryName=[[UILabel alloc] init];
            categoryName.text=model.category_name;
            categoryName.font=[UIFont systemFontOfSize:17];
            categoryName.textColor=[UIColor colorWithHexString:@"#121212"];
            [headerView addSubview:categoryName];
            [categoryName mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(img).with.offset(10);
                make.centerY.equalTo(img);
            }];
        }
        return headerView;
    }
    if ([kind isEqualToString:UICollectionElementKindSectionFooter]){
        for (UIView *view in headerView.subviews) {
            [view removeFromSuperview];
        }
        footerView.backgroundColor=[UIColor whiteColor];
        
        //更多按钮
        UIButton *moreBut=[UIButton buttonWithType:UIButtonTypeCustom];
        [moreBut setImage:[UIImage imageNamed:@"下拉"] forState:UIControlStateNormal];
        [moreBut setTitle:@"More" forState:UIControlStateNormal];
        moreBut.titleLabel.font=[UIFont systemFontOfSize:13];
        
        [moreBut setTitleColor:[UIColor colorWithHexString:@"#535353"] forState:UIControlStateNormal];
        
        [footerView addSubview:moreBut];
        [moreBut mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(footerView);
            make.centerX.equalTo(footerView);
            make.height.mas_offset(20);
            //            make.width.mas_offset(60);
        }];
        [moreBut layoutIfNeeded];
        moreBut.contentHorizontalAlignment=UIControlContentHorizontalAlignmentCenter;
        [moreBut layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:5];
        return footerView;
    }
    return nil;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    CategoryModel *model=self.categoryArry[indexPath.section];
    GoodsModel *goodsModel=model.goods_list[indexPath.row];
    if(self.delageta && [self.delageta respondsToSelector:@selector(didSelectRowAtIndexPath:)]){
        [self.delageta didSelectRowAtIndexPath:goodsModel.uid];
    }
}
#pragma mark  DZNEmptyDataSetDelegate
- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return -22;
}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    switch (self.emptyType) {
        case EmptyDataSetNone:
            return nil;
            break;
        case EmptyDataSetNoData:
            
            return [UIImage imageNamed:@"分类缺失"];
            break;
        case EmptyDataSetNoNetwork:
            
            return [UIImage imageNamed:@"断网"];
            break;
    }
}
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    
    switch (self.emptyType) {
        case EmptyDataSetNone:
            return NO;
            break;
        case EmptyDataSetNoData:
            return YES;
            break;
        case EmptyDataSetNoNetwork:
            return NO;
            break;
    }
}
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView {
    if (self.emptyType==EmptyDataSetNone) {
        UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [activityView startAnimating];
        return activityView;
    }else{
        return nil;
    }
}
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    if (self.emptyType==EmptyDataSetNoData) {
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@",Localized(@"当前分类暂无信息！"),Localized(@"先去其他地方逛逛吧。")]];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:22],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#E6963F"]} range:NSMakeRange(0, [Localized(@"当前分类暂无信息！") length])];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#C2AA93"]} range:NSMakeRange([Localized(@"当前分类暂无信息！") length], [Localized(@"先去其他地方逛逛吧。") length])];
        return currentPriceStr;
    }
    if (self.emptyType==EmptyDataSetNoNetwork){
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@",Localized(@"您的网络不给力啊!"),Localized(@"请您检查是否联网。")]];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:22],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#E6963F"]} range:NSMakeRange(0, [Localized(@"您的网络不给力啊!") length])];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#C2AA93"]} range:NSMakeRange([Localized(@"您的网络不给力啊!") length], [Localized(@"请您检查是否联网。") length])];
        return currentPriceStr;
    }
    return nil;
}
- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state {
    if (self.emptyType==EmptyDataSetNoNetwork){
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:Localized(@"重新加载")];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor whiteColor]} range:NSMakeRange(0, [Localized(@"重新加载") length])];
        return currentPriceStr;
    }else{
        return nil;
    }
    
}

#pragma mark - DZNEmptyDataSetDelegate
- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button {
    //    [self loadDataWithGet_goods];
}

- (void)emptyDataSetWillAppear:(UIScrollView *)scrollView {
    self.collectionView.contentOffset = CGPointZero;
}

-(UICollectionView *)collectionView{
    if (!_collectionView) {
        //1.初始化layout
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        //设置collectionView滚动方向
        //    [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        //设置headerView的尺寸大小
        layout.headerReferenceSize = CGSizeMake(SCREEN_WIDTH, 200);
        //该方法也可以设置itemSize
        layout.itemSize =CGSizeMake(110, 150);
        
        //2.初始化collectionView
        _collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor groupTableViewBackgroundColor];
        
        //3.注册collectionViewCell
        //注意，此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致 均为 cellId
        [_collectionView registerClass:[GoodsListCell class] forCellWithReuseIdentifier:@"cellId"];
        
        _collectionView.showsVerticalScrollIndicator=NO;
        //注册headerView  此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致  均为reusableView
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerSelectType"];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerDisplay"];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"FooterSelectType"];
        //4.设置代理
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.emptyDataSetSource=self;
        _collectionView.emptyDataSetDelegate=self;
    }
    return _collectionView;
}
-(NSMutableArray *)categoryArry{
    if (!_categoryArry) {
        _categoryArry=[[NSMutableArray alloc] init];
    }
    return _categoryArry;
}
-(NSMutableArray *)goodsArry{
    if (!_goodsArry) {
        _goodsArry=[[NSMutableArray alloc] init];
    }
    return _goodsArry;
}
-(NSMutableArray *)cycleArry{
    if (!_cycleArry) {
        _cycleArry=[[NSMutableArray alloc] init];
    }
    return _cycleArry;
}
@end
